<?php
class tls_mysql{
	var $host = '';
	var $user = '';
	var $password = '';
	var $database = '';
	var $persist = false;
	var $conn = NULL;
	var $result = false;
	var $fields;
	var $check_fields;
	var $tbname;
	var $addNewFlag = false;
	var $new = false;
	var $opened = false; //标志已经连接过一次

	public function __construct($host="", $user="", $password="", $dbname="", $open=false, $new=false){
		 ($host != "") && ($this->host = $host);
		 ($user != "") && ($this->user = $user);
		 ($password != "") && ($this->password = $password);
		 ($dbname != "") && ($this->database = $dbname);
		 $this->new = $new;
		 $open && $this->open();
	}
	public function open($host="", $user="", $password="", $dbname=""){
		if(! $this->opened){
			($host != "") && ($this->host = $host);
			($user != "") && ($this->user = $user);
			($password != "") && ($this->password = $password);
			($dbname != "") && ($this->database = $dbname);

			$this->opened = true; //标志已经连接过一次了

			if($this->connect() === false){return false;}
			if($this->select_db() === false){return false;}
		}
		return $this->conn;
	}
	public function set_host($host, $user, $password, $dbname){
		$this->host = $host;
		$this->user = $user;
		$this->password = $password;
		$this->database = $dbname;
	}
	public function affectedRows(){
		return mysql_affected_rows( $this->conn);
	}
	public function close(){
		if( $this->opened){
			$this->opened = false;
			mysql_close( $this->conn);
		}
	}
	public function connect(){
		if(is_resource($this->conn)){
			return true;
		}
		if ($this->persist){
			( $this->conn = mysql_pconnect($this->host, $this->user, $this->password) ) or $this->errorlog("mysql_pconnect: $this->host, $this->user");
		}else{
			( $this->conn = mysql_connect($this->host, $this->user, $this->password, $this->new) ) or $this->errorlog("mysql_connect: $this->host, $this->user");
		}
		if(! is_resource( $this->conn)){
			return false;
		}/*elseif( mysql_get_server_info() > '4.1'){
			$this->query("SET SQL_MODE='',CHARACTER_SET_CONNECTION='utf8',CHARACTER_SET_RESULTS='utf8',CHARACTER_SET_CLIENT='binary',NAMES 'utf8'");
		}*/
		return true;
	}
	public function select_db( $dbname=""){
		$dbname = $this->database = (($dbname == "") ? $this->database : $dbname);
		return  $dbname=='' ? true : mysql_select_db($dbname, $this->conn);
	}
	public function create_db( $dbname=""){
		$dbname = $this->database = (($dbname == "") ? $this->database : $dbname);
		return $this->query("CREATE DATABASE ".$dbname);
	}
	public function drop_db( $dbname=""){
		$dbname = $this->database = (($dbname == "") ? $this->database : $dbname);
		return $this->query("DROP DATABASE " . $dbname);
	}
	public function error(){
	    return mysql_error();
	}
	public function errorno(){
	    return mysql_errno();
	}
	var $last_sql = '';
	public function getLastSql() {
		return $this->last_sql;
	}
	public function query($sql){
	    $this->last_sql = $sql;
	    $this->opened or $this->open(); //自动连接
	    ( $this->result = mysql_query($sql, $this->conn) ) or $this->errorlog( $sql);
	    return $this->result;
	}
	public function numRows( $result=null){
		is_resource($result) or ($result = $this->result);
	    return mysql_num_rows($result);
	}
	public function fieldName($field, $result=null){
		is_resource($result) or ($result = $this->result);
		return mysql_field_name($result,$field);
	}
	public function insertID(){
	    return mysql_insert_id( $this->conn);
	}
	public function data_seek($arg1, $row=0){
		$result = is_resource( $arg1) ? $arg1 : $this->result;

		if(!is_resource($arg1) && !is_null($arg1)){
			$row = $arg1;
		}

		return mysql_data_seek($result,$row);
	}
	public function fetchRow($result=null){
		is_resource($result) or ($result = $this->result);
	    return mysql_fetch_row($result);
	}
	public function fetchObject( $result=null){
		is_resource($result) or ($result = $this->result);
	    return mysql_fetch_object($result);
	}
	public function fetchArray($arg1=null, $mode=MYSQL_ASSOC){
		$result = is_resource( $arg1) ? $arg1 : $this->result;

		if(!is_resource($arg1) && !is_null($arg1))
			$mode = $arg1;
		$array = mysql_fetch_array($result, $mode);
	    return is_array( $array) ? $array : array();
	}
	public function fetchAssoc( $result=null){
		if(!is_resource($result))
			$result = $this->result;
	    return mysql_fetch_assoc($result);
	}
	public function freeResult( $result=null){
		is_resource($result) or ($result = $this->result);
	    return mysql_free_result( $result);
	}
	public function getSingleResult( $sql){
		$result = $this->query( $sql);
		$row = $this->fetchArray($result, MYSQL_NUM);
		return $row[0];
	}
	public function addNew( $table_name){
		$this->fields = array();
		$this->addNewFlag = true;
		$this->tbname = $table_name;
	}
	public function edit($table_name){
		$this->fields = array();
		$this->check_fields = array();
		$this->addNewFlag = false;
		$this->tbname = $table_name;
	}
	public function update(){
		foreach((array)$this->fields as $field_name => $value){
			$qry .= $field_name."='".$value."',";
		}
		$qry = substr($qry, 0, strlen($qry)-1);

		if($this->addNewFlag){
			$qry="INSERT INTO ".$this->tbname." SET " . $qry;
		}else{
			$qry="UPDATE ".$this->tbname." SET ".$qry;
			if(count($this->check_fields)>0 && is_array($this->check_fields)){
			   $qry.=" WHERE ";
			   foreach($this->check_fields as $field_name=>$value)
			       $qry.=$field_name."='".$value."' AND ";
			   $qry=substr($qry,0,strlen($qry)-5);
			}else if(! empty($this->check_fields)){
			   $qry .= " WHERE ".$this->check_fields." ";
			}
		}
		return $this->query($qry);
	}
	public function insert($tbl, $arrData){
		$sql = "INSERT INTO $tbl SET ";
		foreach ((array)$arrData as $key => $value){
			$sql .= "`$key`='$value',";
		}

		$this->query(substr($sql,0,-1));
		return $this->insertID();
	}
	public function getAll($sql, $mode=MYSQL_ASSOC){
		$result = $this->query( $sql);
		$temp = array();
		while ($array = $this->fetchArray($result,$mode)) {
			$temp[] = $array;
		}
		return $temp;
	}
	public function getOne($sql, $mode=MYSQL_ASSOC){
		$result = $this->query( $sql);
		return $this->fetchArray($result,$mode);
	}
	public function fromOneTable($tbl, $where=1, $item=array('*'), $multi=0, $mode=MYSQL_ASSOC){
		$query = "SELECT ";
		foreach ((array)$item as $key => $value){
			$query .= $value . ',';
		}
		$query = substr($query, 0, -1) . " FROM $tbl WHERE $where" . ($multi ? '' : ' Limit 1');
		return $multi ? $this->getAll($query, $mode) : $this->getOne($query, $mode);
	}

	/**
	 * 缓存多行数据
	 */
	public function getCacheAll($sql, $expire, $mode=MYSQL_ASSOC, $key=false){
		$key = $key===false ? md5($sql) : $key;
		if( ($temp = ocache::mysql()->get($key)) === false){
			$temp = $this->getAll($sql, $mode);
			ocache::mysql()->set($key, $temp, $expire);
		}
		return $temp;
	}
	/**
	 * 缓存一行数据
	 */
	public function getCacheOne($sql, $expire, $mode=MYSQL_ASSOC, $key=false){
		$key = $key===false ? md5($sql) : $key;
		if( ($temp = ocache::mysql()->get($key)) === false){
			$temp = $this->getOne($sql, $mode);
			ocache::mysql()->set($key, $temp, $expire);
		}
		return $temp;
	}

	/**
	 * 安全性检测.调用escape存入的,一定要调unescape取出
	 */
	public function escape( $string){
		return mysql_escape_string( trim($string));
	}
	public function unescape( $string){
		return stripslashes( $string);
	}

	/**
	 * 事务处理章节
	 */
	public function Start(){
		$this->query("START TRANSACTION");
	}
	public function Commit(){
		$this->query("COMMIT");
	}
	public function CommitId(){
		$aId = $this->getOne('SELECT LAST_INSERT_ID()', MYSQL_NUM);
		return (int)$aId[0];
	}
	public function Rollback(){
		$this->query("ROLLBACK");
	}
	private function errorlog( $msg='' ){
//		$error = date('Y-m-d H:i:s') . ":\n:" . $this->errorno() . $this->error() . $msg . ";\n";
//		$file = dirname(__FILE__) . '/../data/sqlerr.txt';
//		file_put_contents($file, "{$error}\n", filesize($file)<32*1024 ? FILE_APPEND : null);
//		die('DB Invalid!!!' . $msg);
//		echo 'DB Invalid!!!' . $msg;
		throw new Exception('DB Invalid!!!' . $msg . '| ' . mysql_error(), "999");
	}
	public function __destruct(){
		$this->close();
	}
}